/**
 * DataSource List Page
 *
 * 数据源列表页面 (FR-001, FR-002, FR-006, FR-007, FR-008)
 * - 数据源列表展示
 * - 筛选、搜索、分页
 * - 批量操作
 * - 创建/编辑/删除
 */

import React, { useState } from 'react'
import {
  Button,
  Table,
  Space,
  Tag,
  Input,
  Select,
  Card,
  Modal,
  Form,
  Tooltip,
  Dropdown,
  message,
} from 'antd'
import type { TableProps, MenuProps } from 'antd'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  PoweroffOutlined,
  CheckCircleOutlined,
  MoreOutlined,
  SearchOutlined,
  ReloadOutlined,
} from '@ant-design/icons'
import {
  useDataSourceList,
  useCreateDataSource,
  useUpdateDataSource,
  useDeleteDataSource,
  useEnableDataSource,
  useDisableDataSource,
  useBatchEnableDataSources,
  useBatchDisableDataSources,
  useBatchDeleteDataSources,
} from '@/hooks/useDataSource'
import DataSourceForm from '@/components/datasource/DataSourceForm'
import {
  DatabaseType,
  DB_TYPE_NAMES,
  type DataSource,
  type DataSourceListParams,
} from '@/services/models/types'

const { Search } = Input
const { confirm } = Modal

const DataSourceListPage: React.FC = () => {
  // 查询参数状态
  const [params, setParams] = useState<DataSourceListParams>({
    page: 0,
    size: 10,
  })

  // 模态框状态
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editingDataSource, setEditingDataSource] = useState<DataSource | null>(null)
  const [form] = Form.useForm()

  // 选中行状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([])

  // Hooks
  const { data, isLoading, isFetching, refetch } = useDataSourceList(params)
  const createMutation = useCreateDataSource()
  const updateMutation = useUpdateDataSource()
  const deleteMutation = useDeleteDataSource()
  const enableMutation = useEnableDataSource()
  const disableMutation = useDisableDataSource()
  const batchEnableMutation = useBatchEnableDataSources()
  const batchDisableMutation = useBatchDisableDataSources()
  const batchDeleteMutation = useBatchDeleteDataSources()

  /**
   * 打开创建模态框
   */
  const handleCreate = () => {
    setEditingDataSource(null)
    form.resetFields()
    setIsModalVisible(true)
  }

  /**
   * 打开编辑模态框
   */
  const handleEdit = (record: DataSource) => {
    setEditingDataSource(record)
    setIsModalVisible(true)
  }

  /**
   * 提交表单
   */
  const handleSubmit = async (values: any) => {
    try {
      if (editingDataSource) {
        await updateMutation.mutateAsync({
          id: editingDataSource.id,
          data: values,
        })
      } else {
        await createMutation.mutateAsync(values)
      }
      setIsModalVisible(false)
      form.resetFields()
    } catch (error) {
      // 错误已在hook中处理
    }
  }

  /**
   * 删除数据源
   */
  const handleDelete = (record: DataSource) => {
    confirm({
      title: `确认删除数据源 "${record.name}"?`,
      content: '删除后将无法恢复,请谨慎操作',
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        await deleteMutation.mutateAsync(record.id)
      },
    })
  }

  /**
   * 启用/禁用数据源
   */
  const handleToggleEnabled = async (record: DataSource) => {
    if (record.enabled) {
      await disableMutation.mutateAsync(record.id)
    } else {
      await enableMutation.mutateAsync(record.id)
    }
  }

  /**
   * 批量操作
   */
  const handleBatchAction = (action: 'enable' | 'disable' | 'delete') => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要操作的数据源')
      return
    }

    const actionMap = {
      enable: {
        title: '批量启用',
        content: `确认启用 ${selectedRowKeys.length} 个数据源?`,
        mutation: batchEnableMutation,
      },
      disable: {
        title: '批量禁用',
        content: `确认禁用 ${selectedRowKeys.length} 个数据源?`,
        mutation: batchDisableMutation,
      },
      delete: {
        title: '批量删除',
        content: `确认删除 ${selectedRowKeys.length} 个数据源? 删除后将无法恢复`,
        mutation: batchDeleteMutation,
      },
    }

    const { title, content, mutation } = actionMap[action]

    confirm({
      title,
      content,
      okText: '确认',
      okType: action === 'delete' ? 'danger' : 'primary',
      cancelText: '取消',
      onOk: async () => {
        await mutation.mutateAsync(selectedRowKeys)
        setSelectedRowKeys([])
      },
    })
  }

  /**
   * 搜索
   */
  const handleSearch = (value: string) => {
    setParams({ ...params, keyword: value || undefined, page: 0 })
  }

  /**
   * 数据库类型筛选
   */
  const handleDbTypeChange = (dbType: DatabaseType | undefined) => {
    setParams({ ...params, dbType, page: 0 })
  }

  /**
   * 状态筛选
   */
  const handleStatusChange = (enabled: boolean | undefined) => {
    setParams({ ...params, enabled, page: 0 })
  }

  /**
   * 表格列定义
   */
  const columns: TableProps<DataSource>['columns'] = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '数据源名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      ellipsis: { showTitle: false },
      render: (text) => (
        <Tooltip title={text}>
          <span>{text}</span>
        </Tooltip>
      ),
    },
    {
      title: '数据库类型',
      dataIndex: 'dbType',
      key: 'dbType',
      width: 120,
      render: (dbType: DatabaseType) => DB_TYPE_NAMES[dbType],
    },
    {
      title: '连接信息',
      key: 'connection',
      width: 250,
      ellipsis: { showTitle: false },
      render: (_, record) => {
        const connectionInfo = `${record.host}:${record.port}/${record.databaseName}`
        return (
          <Tooltip title={connectionInfo}>
            <span>{connectionInfo}</span>
          </Tooltip>
        )
      },
    },
    {
      title: '状态',
      key: 'status',
      width: 100,
      render: (_, record) => {
        return record.enabled ? (
          <Tag color="success">已启用</Tag>
        ) : (
          <Tag color="default">已禁用</Tag>
        )
      },
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: { showTitle: false },
      render: (text) => (
        <Tooltip title={text}>
          <span>{text || '-'}</span>
        </Tooltip>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (text) => new Date(text).toLocaleString('zh-CN'),
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      fixed: 'right',
      render: (_, record) => {
        const menuItems: MenuProps['items'] = [
          {
            key: 'edit',
            label: '编辑',
            icon: <EditOutlined />,
            onClick: () => handleEdit(record),
          },
          {
            key: 'toggle',
            label: record.enabled ? '禁用' : '启用',
            icon: <PoweroffOutlined />,
            onClick: () => handleToggleEnabled(record),
          },
          {
            type: 'divider',
          },
          {
            key: 'delete',
            label: '删除',
            icon: <DeleteOutlined />,
            danger: true,
            onClick: () => handleDelete(record),
          },
        ]

        return (
          <Space size="small">
            <Button size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
              编辑
            </Button>
            <Dropdown menu={{ items: menuItems }} trigger={['click']}>
              <Button size="small" icon={<MoreOutlined />} />
            </Dropdown>
          </Space>
        )
      },
    },
  ]

  /**
   * 行选择配置
   */
  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: React.Key[]) => setSelectedRowKeys(keys as number[]),
  }

  return (
    <div>
      <Card>
        {/* 工具栏 */}
        <Space direction="vertical" size="middle" style={{ width: '100%' }}>
          <Space wrap>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
              新建数据源
            </Button>
            <Button
              icon={<CheckCircleOutlined />}
              onClick={() => handleBatchAction('enable')}
              disabled={selectedRowKeys.length === 0}
            >
              批量启用
            </Button>
            <Button
              icon={<PoweroffOutlined />}
              onClick={() => handleBatchAction('disable')}
              disabled={selectedRowKeys.length === 0}
            >
              批量禁用
            </Button>
            <Button
              danger
              icon={<DeleteOutlined />}
              onClick={() => handleBatchAction('delete')}
              disabled={selectedRowKeys.length === 0}
            >
              批量删除
            </Button>
            <Button icon={<ReloadOutlined />} onClick={() => refetch()} loading={isFetching}>
              刷新
            </Button>
          </Space>

          {/* 筛选器 */}
          <Space wrap>
            <Search
              placeholder="搜索数据源名称或描述"
              allowClear
              style={{ width: 300 }}
              onSearch={handleSearch}
              enterButton={<SearchOutlined />}
            />
            <Select
              placeholder="数据库类型"
              allowClear
              style={{ width: 150 }}
              onChange={handleDbTypeChange}
              options={[
                { label: '全部', value: undefined },
                ...Object.entries(DB_TYPE_NAMES).map(([value, label]) => ({ value, label })),
              ]}
            />
            <Select
              placeholder="状态"
              allowClear
              style={{ width: 120 }}
              onChange={handleStatusChange}
              options={[
                { label: '全部', value: undefined },
                { label: '已启用', value: true },
                { label: '已禁用', value: false },
              ]}
            />
          </Space>
        </Space>

        {/* 表格 */}
        <Table
          rowKey="id"
          columns={columns}
          dataSource={data?.content || []}
          loading={isLoading}
          rowSelection={rowSelection}
          pagination={{
            current: (params.page || 0) + 1,
            pageSize: params.size || 10,
            total: data?.totalElements || 0,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page, pageSize) => {
              setParams({ ...params, page: page - 1, size: pageSize })
            },
          }}
          scroll={{ x: 1400 }}
          style={{ marginTop: 16 }}
        />
      </Card>

      {/* 创建/编辑模态框 */}
      <Modal
        title={editingDataSource ? '编辑数据源' : '创建数据源'}
        open={isModalVisible}
        onCancel={() => {
          setIsModalVisible(false)
          form.resetFields()
        }}
        footer={null}
        width={600}
        destroyOnClose
      >
        <DataSourceForm
          form={form}
          initialValues={editingDataSource || undefined}
          isEditMode={!!editingDataSource}
          onSubmit={handleSubmit}
          onCancel={() => {
            setIsModalVisible(false)
            form.resetFields()
          }}
          submitting={createMutation.isPending || updateMutation.isPending}
        />
      </Modal>
    </div>
  )
}

export default DataSourceListPage
